// pages/new/new.js
var app = getApp();
const db = wx.cloud.database()
const eve = db.collection('eve')
const user = db.collection('user')
import Toast from '../../vant-weapp/toast/toast';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    name: '',
    addr: '',
    max_num: '',
    start_time: '',
    end_time: '',
    start_time_date: '',
    end_time_date: '',
    qqgroup: '',
    qqwx: '',
    good_name: '',
    good_price: '',
    des: '',
    show_popup_start_time: false,
    show_popup_end_time: false,
    activity_type: 0,
    currentDate: new Date().getTime(),
    fileList: [],
    folder: 'uploader',
    tmpUrlArr: [],
  },

  onChange_name(event) {
    this.setData({ name: event.detail})
  },

  onChange_addr(event) {
    this.setData({ addr: event.detail})
  },

  onChange_max_num(event) {
    this.setData({ max_num: event.detail})
  },

  onChange_qqwx(event) {
    this.setData({ qqwx: event.detail})
  },

  onChange_qqgroup(event) {
    this.setData({ qqgroup: event.detail})
  },

  onChange_good_name(event) {
    this.setData({ good_name: event.detail})
  },

  onChange_good_price(event) {
    this.setData({ good_price: event.detail})
  },

  onChange_des(event) {
    this.setData({ des: event.detail})
  },

  onChangeSwiper(event) {
    if (event.detail.source=="touch") {
      switch (event.detail.current) {
        case 0:
          this.setData({ activity_type: 0})
          break;
        case 1:
          this.setData({ activity_type: 1})
          break;
        case 2:
          this.setData({ activity_type: 2})
          break
        default:
          break;
      }
    }
  },


  //点击选择活动开始时间
  onClick_start_time() {
    this.setData({ show_popup_start_time: true });
  },

  //点击选择活动结束时间
  onClick_end_time() {
    this.setData({ show_popup_end_time: true });
  },

  //确认选择活动开始时间
  onConfirm_start_time(event) {
    var date = new Date(event.detail);
    this.setData({ 
      start_time: this.formateDate(date), 
      start_time_date: date, 
      show_popup_start_time: false
    });
  },

  //确认选择活动结束时间
  onConfirm_end_time(event) {
    var date = new Date(event.detail);
    this.setData({
       end_time: this.formateDate(date) ,
       end_time_date: date,
       show_popup_end_time: false
    });
  },
  //格式化时间输出
  formateDate: function (date) {
    var y = date.getFullYear();
    var m = (Number(date.getMonth()) + 1);
    var d = date.getDate();
    var h = date.getHours();
    var mi = Number(date.getMinutes());
    if (mi<10)
      mi = '0' + mi;
    return y+"/"+m+"/"+d+"/"+h+":"+mi;
  },

  //关闭选择时间界面
  onClose_popup_start_time() {
    this.setData({ show_popup_start_time: false });
  },
  onClose_popup_end_time() {
    this.setData({ show_popup_end_time: false });
  },

  afterRead(event) {
    const file = event.detail.file[0];
    this.data.fileList.push(file);
    var files = this.data.fileList;
    this.setData({
      fileList: files ,
    })
  },

  uploadToCloud(check_result) {
    wx.cloud.init();

    var path = this.data.folder;
    this.setData({
      path
    })
    if (this.data.fileList.length == 0) {
      this.uploadData(check_result);
      return true;
    } else {
      var fileList = this.data.fileList;
      var date = new Date().getTime();
      const uploadTasks = fileList.map((file, index) => this.uploadFilePromise(`${path}/${date}-${app.globalData.open_id}-${index}`, file));
      Promise.all(uploadTasks)
        .then(data => {
          wx.showToast({ title: '图片上传成功', icon: 'none' });
          var newFileList = data.map(item => {
            return item.fileID
          });
          console.log(newFileList);
          this.setData({ 
            tmpUrlArr: newFileList,    
          });
          this.uploadData(check_result);
          return true;
        })
        .catch(e => {
          Toast.clear();
          wx.showToast({ title: '上传失败', icon: 'none' });
          console.log(e);
          return false;
        });
    }
  },
  getImageInfo(chooseResult) {
    return new Promise((resolve, reject) => {
      wx.getImageInfo({
        src: chooseResult.url,
        success (res) {
          resolve(res.type)
        },
        fail (err) {
          console.log(err)
          reject(err)
        }
      })
    })
  },
  
  async uploadFilePromise(fileName, chooseResult) {
    var type = await this.getImageInfo(chooseResult);
    return wx.cloud.uploadFile({
      cloudPath: fileName + '.' + type,
      filePath: chooseResult.url,
    });
  },

  deleteImg(event) {
    var index = event.detail.index;
    var newfile = this.data.fileList;
    newfile.splice(index,1);
    this.setData({
      fileList: newfile
    })
  },

  checkInput() {
    if (this.data.activity_type == 0) {
      if (this.data.name == null || this.data.name == '') {
        wx.showToast({ title: '未填写活动名称！', icon: 'none' });
        return -1;
      }
      if (this.data.addr == null || this.data.addr == '') {
        wx.showToast({ title: '未填写地点！', icon: 'none' });
        return -1;
      }
      if (this.data.max_num == null || this.data.max_num == '') {
        wx.showToast({ title: '未填写人数！', icon: 'none' });
        return -1;
      }
      if (Number.isInteger(Number(this.data.max_num)) == false) {
        wx.showToast({ title: '人数必须是纯数字！', icon: 'none' });
        return -1;
      }
      if (this.data.start_time == null || this.data.start_time == '') {
        wx.showToast({ title: '未选择开始时间！', icon: 'none' });
        return -1;
      }
      if (this.data.qqgroup == null || this.data.qqgroup == '') {
        wx.showToast({ title: '未填写QQ群号！', icon: 'none' });
        return -1;
      }
      if (Number.isInteger(Number(this.data.qqgroup)) == false) {
        wx.showToast({ title: 'QQ群号必须是纯数字！', icon: 'none' });
        return -1;
      }
      if (this.data.des == null || this.data.des == '') {
        wx.showToast({ title: '未填写简介！', icon: 'none' });
        return -1;
      }
      return 0;
    } else if (this.data.activity_type == 1) {
      if (this.data.name == null || this.data.name == '') {
        wx.showToast({ title: '未填写活动名称！', icon: 'none' });
        return -1;
        }
        if (this.data.good_name == null || this.data.good_name == '') {
          wx.showToast({ title: '未填写物品名称！', icon: 'none' });
          return -1;
        }
        if (Number.isNaN(this.data.max_num)) {
          wx.showToast({ title: '价格必须是数字！', icon: 'none' });
          return -1;
        }
        if (this.data.qqwx == null || this.data.qqwx == '') {
          wx.showToast({ title: '未填写联系方式！', icon: 'none' });
          return -1;
        }
        if (this.data.des == null || this.data.des == '') {
          wx.showToast({ title: '未填写简介！', icon: 'none' });
          return -1;
        }
        return 1;
    } else if (this.data.activity_type == 2) {
      if (this.data.name == null || this.data.name == '') {
        wx.showToast({ title: '未填写活动名称！', icon: 'none' });
        return -1;
      }
      if (this.data.addr == null || this.data.addr == '') {
        wx.showToast({ title: '未填写地点！', icon: 'none' });
        return -1;
      }
      if (this.data.good_name == null || this.data.good_name == '') {
        wx.showToast({ title: '未填写物品名称！', icon: 'none' });
        return -1;
      }
      if (this.data.qqwx == null || this.data.qqwx == '') {
        wx.showToast({ title: '未填写联系方式！', icon: 'none' });
        return -1;
      }
      if (this.data.des == null || this.data.des == '') {
        wx.showToast({ title: '未填写简介！', icon: 'none' });
        return -1;
      }
      return 2;
    }  else {
      wx.showToast({ title: '创建活动失败！', icon: 'none' });
      console.log(this.data.activity_type);
      return -1;
    }
  },

  uploadData(check_result) {
    const _ = db.command
    var that= this;
    if (check_result == 0) {
      eve.add({
        data:{
          type: '1',
          name: this.data.name,
          addr: this.data.addr,
          max_num: Number(this.data.max_num),
          start_time: this.data.start_time_date,
          end_time: this.data.end_time_date,
          qqgroup: this.data.qqgroup,
          des: this.data.des,
          pic: this.data.tmpUrlArr,
          num: 0,
          list: [],
          bool_end: false,
        },
        success: function(res){
          Toast.clear();
          wx.showToast({ title: '创建活动成功！', icon: 'success' });
          that.resetData();
        }
      })
    } else if (check_result == 1) {
      eve.add({
        data:{
          type: '2',
          name: this.data.name,
          good_name: this.data.good_name,
          good_price: Number(this.data.good_price),
          qqwx: this.data.qqwx,
          des: this.data.des,
          pic: this.data.tmpUrlArr,
          bool_end: false,
          start_time: new Date(),
        },
        success: function(res){
          Toast.clear();
          wx.showToast({ title: '创建活动成功！', icon: 'success' });
          that.resetData();
        }
      })
    } else if (check_result == 2) {
      eve.add({
        data:{
          type: '3',
          name: this.data.name,
          addr: this.data.addr,
          good_name: this.data.good_name,
          qqwx: this.data.qqwx,
          des: this.data.des,
          pic: this.data.tmpUrlArr,
          bool_end: false,
          start_time: new Date(),
        },
        success: function(res){
          Toast.clear();
          wx.showToast({ title: '创建活动成功！', icon: 'success' });
          that.resetData();
        }
      })
    } else {
      Toast.clear();
      wx.showToast({ title: '创建活动失败！', icon: 'none' });
    }
  },

  //按下创建按钮
  onClickButton(){
    var check_result = this.checkInput();
    if (check_result >= 0 ) {
      Toast.loading({
        duration: 0,
        mask: true,
        message: '数据提交中...',
        forbidClick: true,
        selector: '#custom-selector',
      });
      this.uploadToCloud(check_result);
      return true;
    } else {
      return false;
    }

    
  },
  resetData() {
    this.setData({
      name: '',
      addr: '',
      max_num: '',
      start_time: '',
      end_time: '',
      start_time_date: '',
      end_time_date: '',
      qqgroup: '',
      qqwx: '',
      good_name: '',
      good_price: '',
      des: '',
      show_popup_start_time: false,
      show_popup_end_time: false,
      activity_type: 0,
      currentDate: new Date().getTime(),
      fileList: [],
      folder: 'uploader',
      tmpUrlArr: [],
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})